#coding: utf-8
import os
from flask import current_app, render_template
from sqlalchemy import *


def exist_config():
    return _exist_config(current_app)


import sys

def _exist_config(app):
    # 检查外部app文件夹中的config.py文件
    if getattr(sys, 'frozen', False):
        # 打包后的环境
        config_path = os.path.join(os.path.dirname(sys.executable), 'config.py')
    else:
        # 开发环境
        config_path = os.path.join(app.root_path, 'config.py')
    return os.path.exists(config_path)


def create_config(username, password, host, port, db):
    data = render_template("admin/start/config.html", username=username,
        password=password, host=host, port=port, db = db)
    # 在外部app文件夹中创建config.py
    if getattr(sys, 'frozen', False):
        # 打包后的环境
        config_dir = os.path.join(os.path.dirname(sys.executable))
        # 确保app文件夹存在
        if not os.path.exists(config_dir):
            os.makedirs(config_dir)
        config_path = os.path.join(config_dir, 'config.py')
    else:
        # 开发环境
        config_path = os.path.join(current_app.root_path, 'config.py')
    fd = open(config_path, "w")
    fd.write(data)
    fd.close()


def create_path(app):
    paths, config = [], app.config
    log_path, _ = os.path.split(config["ERROR_LOG"])
    paths.append(os.path.join(app.root_path, log_path))

    paths.append(os.path.join(app.static_folder, config["AVATAR_PATH"]))
    paths.append(os.path.join(app.static_folder, config["TMP_PATH"]))
    paths.append(os.path.join(app.static_folder, config["IMAGE_PATH"]))
    paths.append(os.path.join(app.static_folder, config["BOOK_COVER_PATH"]))
    for path in paths:
        if not os.path.exists(path):
            os.makedirs(path)


def connect_mysql(url):
    """1049 => 数据库不存在
       2005 => 主机地址错误
       1045 => 用户名密码错误"""
    try:
        engine = create_engine(url)
        connection = engine.connect()
        connection.close()
    except Exception as e:
        # 处理OperationalError异常，提取错误代码
        if hasattr(e, 'orig'):
            orig_error = e.orig
            if isinstance(orig_error, tuple) and len(orig_error) >= 2:
                code, _ = orig_error[:2]
                return code
            elif hasattr(orig_error, 'args') and len(orig_error.args) >= 2:
                code, _ = orig_error.args[:2]
                return code
            else:
                # 如果无法提取错误代码，返回默认错误代码
                return getattr(orig_error, 'code', 1)
        return 1
    return 0


def create_tables(db):
    db.create_all()


def exist_table(app):
    url = app.config["SQLALCHEMY_DATABASE_URI"]
    return _exist_table(url)


def _exist_table(url):
    from app.models.site import SiteMeta
    from sqlalchemy import inspect
    engine = create_engine(url)
    inspector = inspect(engine)
    if inspector.has_table(SiteMeta.__tablename__):
        return True
    return False


def set_site(app):
    from app.models.site import SiteMeta
    metas = SiteMeta.all()
    metas = dict([(meta.name, meta.value) for meta in metas])
    app.site = metas


def load_site(app):
    with app.app_context():
        set_site(app)
        def site_context_processor():
            return dict(site=app.site)
        app.context_processor(site_context_processor)


